package com.metadata_system.api_server.system_server;

import com.metadata_system.common.request.UserOperationLogListParams;
import com.metadata_system.common.service.UserOperationLogService;
import org.apache.commons.lang.StringUtils;
import com.metadata_system.api.annotations.ApiCheckSign;
import com.metadata_system.api.annotations.CheckTokenUser;
import com.metadata_system.common.db.entity.User;
import com.metadata_system.common.dto.ApiResult;
import com.metadata_system.common.enums.AllConst;
import com.metadata_system.common.http.request_dto.LoginUserRequest;
import com.metadata_system.common.request.UserListRequest;
import com.metadata_system.common.request.UserLoginLogListParams;
import com.metadata_system.common.service.CommonUserService;
import com.metadata_system.common.service.UserLoginLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController("systemUserController")
@RequestMapping("/api/system-server/v001/User")
public class UserController {

    @Autowired
    CommonUserService userService;
    @Autowired
    UserLoginLogService userLoginLogService;
    @Autowired
    CommonUserService commonUserService;
    @Autowired
    LoginUserRequest loginUserRequest;


    @RequestMapping(value = "getList", method = {RequestMethod.GET, RequestMethod.POST})
    @CheckTokenUser(role = {"Super","System"})
    @ApiCheckSign
    public Object getList(
            @RequestParam(required = false) String keywords,
            @RequestParam(required = false) String filterIds,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer params,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String userType,
            @RequestParam(required = false) String role,
            @RequestParam(required = false) String createdTime,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String sortProp,
            @RequestParam(required = false) String sortOrder
    ) {

        return userService.getList(
                UserListRequest.builder()
                        .keywords(keywords)
                        .filterIds(filterIds)
                        .username(username)
                        .params(params)
                        .name(name)
                        .role(role)
                        .currRole(this.userService.getUserRole(loginUserRequest.getTokenUser()))
                        .userType(userType)
                        .status(status)
                        .createdTime(createdTime)
                        .page(page)
                        .pageSize(pageSize)
                        .sortProp(sortProp)
                        .sortOrder(sortOrder)
                        .build()
        );
    }


    @RequestMapping(value = "create", method = {RequestMethod.GET, RequestMethod.POST})
    @CheckTokenUser(role = {"Super","System"})
    @Transactional
    @ApiCheckSign
    public Object create(
            @RequestParam String username,
            @RequestParam String avatar,
            @RequestParam String password,
            @RequestParam(required = false) String role,
            @RequestParam String name,
            @RequestParam(required = false) Integer isLogicToolAccess
    ) {

        String currUserRole = this.userService.getUserRole(loginUserRequest.getTokenUser());
        if(currUserRole.equals("User")){
            return ApiResult.error("只有【超级管理员/系统管理员】才能创建: 【用户】");
        }
        ApiResult apiResult = this.userService.create(
                User.builder()
                        .username(username)
                        .password(password)
                        .role(role)
                        .name(name)
                        .avatar(avatar)
                        .isLogicToolAccess(isLogicToolAccess)
                        .build(),
                currUserRole,
                this.loginUserRequest.getTokenUser().decodeID());
        if (apiResult.getCode() > 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResult;
    }


    @RequestMapping(value = "update", method = {RequestMethod.GET, RequestMethod.POST})
    @CheckTokenUser(role = {"Super","System"})
    @Transactional
    @ApiCheckSign
    public Object update(
            @RequestParam Integer id,
            @RequestParam(required = false) String avatar,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String role,
            @RequestParam(required = false) Integer isLogicToolAccess
    ) {
        String currUserRole = this.userService.getUserRole(loginUserRequest.getTokenUser());
        if(currUserRole.equals("User")){
            return ApiResult.error("只有【超级管理员/系统管理员】才能更新: 【用户】");
        }
        if(!StringUtils.isBlank(avatar)){
            avatar=avatar.replace(AllConst.OssURL,"");
        }
        ApiResult apiResult = this.userService.update(
                User.builder()
                        .id(id)
                        .name(name)
                        .status(status)
                        .role(role)
                        .isLogicToolAccess(isLogicToolAccess)
                        .avatar(avatar)
                        .build(),
                currUserRole,
                this.loginUserRequest.getTokenUser().decodeID()
        );
        if (apiResult.getCode() > 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResult;
    }


    @RequestMapping(value = "delete", method = {RequestMethod.GET, RequestMethod.POST})
    @CheckTokenUser(role = {"Super","System"})
    @Transactional
    @ApiCheckSign
    public ApiResult delete(
            @RequestParam Integer id
    ) {
        String currUserRole = this.userService.getUserRole(loginUserRequest.getTokenUser());
        if(currUserRole.equals("User")){
            return ApiResult.error("只有【超级管理员/系统管理员】才能删除: 【用户】");
        }
        ApiResult apiResult = this.userService.deleteUser(id, currUserRole, this.loginUserRequest.getTokenUser().decodeID());
        if (apiResult.getCode() > 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return apiResult;
    }

    @RequestMapping(value = "getLoginLogList", method = {RequestMethod.GET, RequestMethod.POST})
    @CheckTokenUser(role = {"Super","System"})
    @ApiCheckSign
    public Object getLoginLogList(
            @RequestParam(required = false) Integer userId,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String role,
            @RequestParam(required = false) String ip,
            @RequestParam(required = false) String deviceId,
            @RequestParam(required = false) String createdTime,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String sortProp,
            @RequestParam(required = false) String sortOrder
    ) {
        return userLoginLogService.getList(
                UserLoginLogListParams.builder()
                        .userId(userId)
                        .username(username)
                        .currRole(this.userService.getUserRole(loginUserRequest.getTokenUser()))
                        .role(role)
                        .ip(ip)
                        .deviceId(deviceId)
                        .status(status)
                        .createdTime(createdTime)
                        .page(page)
                        .pageSize(pageSize)
                        .sortProp(sortProp)
                        .sortOrder(sortOrder)
                        .build()
        );
    }

    @RequestMapping(value = "getOperationLogList",method = {RequestMethod.GET, RequestMethod.POST})
    @CheckTokenUser(role = {"Super","System"})
    @Transactional
    public ApiResult getOperationLogList(
            @RequestParam(required = false) Integer userId,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String role,
            @RequestParam(required = false) String ip,
            @RequestParam(required = false) String content,
            @RequestParam(required = false) String createdTime,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String sortProp,
            @RequestParam(required = false) String sortOrder
    ){
        return userOperationLogService.getList(
                UserOperationLogListParams.builder()
                        .userId(userId)
                        .username(username)
                        .role(role)
                        .ip(ip)
                        .content(content)
                        .createdTime(createdTime)
                        .page(page)
                        .pageSize(pageSize)
                        .sortProp(sortProp)
                        .sortOrder(sortOrder)
                        .currRole(this.userService.getUserRole(loginUserRequest.getTokenUser()))
                        .build()
        );
    }

    @Autowired
    UserOperationLogService userOperationLogService;


    @RequestMapping(value = "clearLoginError", method = {RequestMethod.GET, RequestMethod.POST})
    @CheckTokenUser(role = {"Super","System"})
    @Transactional
    @ApiCheckSign
    public Object clearLoginError(
            @RequestParam Integer id
    ) {
        String currUserRole = this.userService.getUserRole(loginUserRequest.getTokenUser());
        if(currUserRole.equals("User")){
            return ApiResult.error("只有【超级管理员/系统管理员】才能清除: 【用户】登录错误次数");
        }
        return this.commonUserService.clearLoginDayError(id,this.loginUserRequest.getTokenUser().decodeID());
    }

}
